package com.tastespot.utils;


import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: 369pro
 * @CreateTime: 2025-05-13
 * @Version: 1.0
 */

public class JsonUtils {
    private JsonUtils(){}
    // Jackson 对象映射器
    private static final ObjectMapper MAPPER = new ObjectMapper();

    /**
     * 将任意对象转换成 Map<String, String>，忽略空值并统一调用 toString()
     *
     * @param obj 待转换的对象
     * @return 字符串 Map
     */
    public static Map<String, String> beanToStringMap(Object obj) {
        // 将对象转换为 Map<String, Object>
        Map<String, Object> temp = MAPPER.convertValue(
                obj,
                new TypeReference<Map<String, Object>>() {}
        );
        // 过滤 null 并调用 toString()
        return temp.entrySet().stream()
                .filter(e -> e.getValue() != null)
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        e -> e.getValue().toString()
                ));
    }
}
